<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        /* div {
            width: 200px;
            height: 200px;
            border: 1px solid #000;
        } */
    </style>
</head>

<body>
    <input type="text" name="" id="" placeholder="请输入你的内容">
    <button>发送</button>
    <div></div>
    <script>
        var input = document.querySelector('input')
        var button = document.querySelector('button')
        var div = document.querySelector('div')


        const TYPE_ENTER = 0
        const TYPE_LEAVE = 1
        const TYPE_MSG = 2

        // 演示websocket在浏览器中如何使用
        // 1、创建websocket服务
        //  参数1：websocket的服务地址
        var ws = new WebSocket("ws://localhost:3000");
        // var ws = new WebSocket("ws://echo.websocket.org");
        // 2、open当服务连接成功是触发 
        ws.addEventListener('open', function () {
            div.innerHTML = '连接成功！'
        })
        // 3、 主动给websocket发消息
        button.addEventListener('click', function () {
            var value = input.value
            ws.send(value)
            input.value = ''
        })
        // 4、 接收websocket服务的数据
        ws.addEventListener('message', function (e) {
            var data = JSON.parse(e.data)
            var dv = document.createElement('div')
            dv.innerText = data.msg + '------------' + data.time
            if (data.type === TYPE_ENTER) {
                dv.style.color = 'green'
            } else if (data.type === TYPE_LEAVE) {
                dv.style.color = 'red'
            }
            div.appendChild(dv)
        })
        // 5、 服务断开
        ws.addEventListener('close', function (e) {
            console.log('服务异常')
        })
    </script>
</body>

</html>